/**
 * 学校和班级选择弹窗组件
 * 支持学校选择和班级筛选,带有流畅的滑动动画
 */

'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { School, ClassFilters } from '@/types/api';
import { getSchools, getClassFilters } from '@/api/v1';
import { X, Building2, GraduationCap, ChevronRight, Search } from 'lucide-react';
import { clsx } from 'clsx';

interface SchoolClassSelectorProps {
  /** 是否打开弹窗 */
  open: boolean;
  /** 弹窗状态变化回调 */
  onOpenChange: (open: boolean) => void;
  /** 选择完成回调 */
  onSelect: (schoolId: number, classCode: string) => void;
  /** 初始学校ID */
  initialSchoolId?: number;
  /** 初始班级编号 */
  initialClassCode?: string;
}

type ViewMode = 'school' | 'class';

export const SchoolClassSelector: React.FC<SchoolClassSelectorProps> = ({
  open,
  onOpenChange,
  onSelect,
  initialSchoolId,
  initialClassCode,
}) => {
  const [viewMode, setViewMode] = useState<ViewMode>('school');
  const [schools, setSchools] = useState<School[]>([]);
  const [selectedSchoolId, setSelectedSchoolId] = useState<number | undefined>(initialSchoolId);
  const [classFilters, setClassFilters] = useState<ClassFilters | null>(null);
  const [selectedFilters, setSelectedFilters] = useState<Record<string, string>>({});
  
  const [loadingSchools, setLoadingSchools] = useState(false);
  const [loadingClasses, setLoadingClasses] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 加载学校列表
  useEffect(() => {
    if (open && viewMode === 'school' && schools.length === 0) {
      loadSchools();
    }
  }, [open, viewMode]);

  // 当有初始学校ID时,直接进入班级选择
  useEffect(() => {
    if (open && initialSchoolId && !initialClassCode) {
      setSelectedSchoolId(initialSchoolId);
      setViewMode('class');
      loadClassFilters(initialSchoolId);
    } else if (open && !initialSchoolId) {
      setViewMode('school');
    }
  }, [open, initialSchoolId, initialClassCode]);

  const loadSchools = async () => {
    setLoadingSchools(true);
    setError(null);
    try {
      const data = await getSchools();
      setSchools(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载学校列表失败');
    } finally {
      setLoadingSchools(false);
    }
  };

  const loadClassFilters = async (schoolId: number, filters: Record<string, string> = {}) => {
    setLoadingClasses(true);
    setError(null);
    try {
      const data = await getClassFilters({
        school_id: schoolId,
        ...filters,
      });
      setClassFilters(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载班级列表失败');
    } finally {
      setLoadingClasses(false);
    }
  };

  const handleSchoolSelect = (school: School) => {
    setSelectedSchoolId(school.id);
    setSelectedFilters({});
    setViewMode('class');
    loadClassFilters(school.id);
  };

  const handleFilterChange = (field: string, value: string) => {
    const newFilters = { ...selectedFilters, [field]: value };
    setSelectedFilters(newFilters);
    if (selectedSchoolId) {
      loadClassFilters(selectedSchoolId, newFilters);
    }
  };

  const handleClassSelect = (classCode: string) => {
    if (selectedSchoolId) {
      onSelect(selectedSchoolId, classCode);
      onOpenChange(false);
      // 重置状态
      setViewMode('school');
      setSelectedFilters({});
      setClassFilters(null);
    }
  };

  const handleBack = () => {
    setViewMode('school');
    setSelectedFilters({});
    setClassFilters(null);
  };

  const handleClose = () => {
    onOpenChange(false);
    // 延迟重置状态,等待动画完成
    setTimeout(() => {
      setViewMode('school');
      setSelectedFilters({});
      setClassFilters(null);
    }, 300);
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* 背景模糊层 */}
      <div
        className="absolute inset-0 backdrop-blur-md bg-white/30 animate-in fade-in duration-300"
        onClick={handleClose}
      />

      {/* 弹窗内容 */}
      <div className="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-300">
        {/* 关闭按钮 */}
        <button
          onClick={handleClose}
          className="absolute top-4 right-4 z-10 p-2 rounded-full bg-gray-100 hover:bg-gray-200 transition-colors"
        >
          <X className="w-5 h-5 text-gray-600" />
        </button>

        {/* 内容容器 - 支持滑动切换 */}
        <div className="relative overflow-hidden">
          {/* 学校选择视图 */}
          <div
            className={clsx(
              'transition-transform duration-300 ease-out',
              viewMode === 'school' ? 'translate-x-0' : '-translate-x-full'
            )}
          >
            <SchoolSelectionView
              schools={schools}
              loading={loadingSchools}
              error={error}
              onSelect={handleSchoolSelect}
              onRetry={loadSchools}
            />
          </div>

          {/* 班级选择视图 */}
          <div
            className={clsx(
              'absolute top-0 left-0 w-full transition-transform duration-300 ease-out',
              viewMode === 'class' ? 'translate-x-0' : 'translate-x-full'
            )}
          >
            <ClassSelectionView
              classFilters={classFilters}
              selectedFilters={selectedFilters}
              loading={loadingClasses}
              error={error}
              onFilterChange={handleFilterChange}
              onClassSelect={handleClassSelect}
              onBack={handleBack}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

/** 筛选按钮组件 */
interface FilterButtonProps {
  filter: {
    field: string;
    title: string;
    options: Array<{ value: string; text: string; count: number }>;
  };
  value: string;
  onChange: (value: string) => void;
}

const FilterButton: React.FC<FilterButtonProps> = ({ filter, value, onChange }) => {
  const [isOpen, setIsOpen] = useState(false);
  const selectedOption = filter.options.find((opt) => opt.value === value);
  const displayText = selectedOption ? selectedOption.text : filter.title;

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={clsx(
          'px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 flex items-center space-x-2 border-2',
          value
            ? 'bg-indigo-500 text-white border-indigo-500 hover:bg-indigo-600'
            : 'bg-white text-gray-700 border-gray-300 hover:border-indigo-400 hover:text-indigo-600'
        )}
      >
        <span>{displayText}</span>
        <ChevronRight
          className={clsx(
            'w-4 h-4 transition-transform duration-200',
            isOpen ? 'rotate-90' : 'rotate-0'
          )}
        />
      </button>

      {/* 下拉选项 */}
      {isOpen && (
        <>
          <div
            className="fixed inset-0 z-10"
            onClick={() => setIsOpen(false)}
          />
          <div className="absolute top-full left-0 mt-2 bg-white rounded-lg shadow-xl border border-gray-200 z-20 min-w-[200px] max-h-[300px] overflow-y-auto">
            <button
              onClick={() => {
                onChange('');
                setIsOpen(false);
              }}
              className="w-full px-4 py-2 text-left text-sm hover:bg-gray-50 transition-colors border-b border-gray-100"
            >
              <span className="text-gray-500">全部</span>
            </button>
            {filter.options.map((option) => (
              <button
                key={option.value}
                onClick={() => {
                  onChange(option.value);
                  setIsOpen(false);
                }}
                className={clsx(
                  'w-full px-4 py-2 text-left text-sm hover:bg-indigo-50 transition-colors flex items-center justify-between',
                  value === option.value && 'bg-indigo-50 text-indigo-600 font-medium'
                )}
              >
                <span>{option.text}</span>
                <span className="text-xs text-gray-400 ml-2">({option.count})</span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

/** 学校选择视图 */
interface SchoolSelectionViewProps {
  schools: School[];
  loading: boolean;
  error: string | null;
  onSelect: (school: School) => void;
  onRetry: () => void;
}

const SchoolSelectionView: React.FC<SchoolSelectionViewProps> = ({
  schools,
  loading,
  error,
  onSelect,
  onRetry,
}) => {
  return (
    <div className="min-h-[500px] flex flex-col">
      {/* 头部 */}
      <div className="bg-gradient-to-br from-blue-500 to-indigo-600 text-white p-8">
        <div className="flex items-center justify-center mb-4">
          <Building2 className="w-12 h-12" />
        </div>
        <h2 className="text-2xl font-bold text-center">选择学校</h2>
        <p className="text-blue-100 text-center mt-2 text-sm">请选择您所在的学校</p>
      </div>

      {/* 内容区域 */}
      <div className="flex-1 p-6 overflow-y-auto max-h-[400px]">
        {loading && <SchoolSkeletonList count={4} />}
        
        {error && (
          <div className="text-center py-8">
            <p className="text-red-500 mb-4">{error}</p>
            <button
              onClick={onRetry}
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            >
              重试
            </button>
          </div>
        )}

        {!loading && !error && schools.length > 0 && (
          <div className="space-y-3">
            {schools.map((school) => (
              <button
                key={school.id}
                onClick={() => onSelect(school)}
                className="w-full p-4 bg-gradient-to-r from-gray-50 to-gray-100 hover:from-blue-50 hover:to-indigo-50 rounded-xl border-2 border-gray-200 hover:border-blue-400 transition-all duration-200 flex items-center justify-between group"
              >
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center group-hover:bg-blue-200 transition-colors">
                    <Building2 className="w-5 h-5 text-blue-600" />
                  </div>
                  <span className="font-medium text-gray-800">{school.name}</span>
                </div>
                <ChevronRight className="w-5 h-5 text-gray-400 group-hover:text-blue-500 transition-colors" />
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

/** 班级选择视图 */
interface ClassSelectionViewProps {
  classFilters: ClassFilters | null;
  selectedFilters: Record<string, string>;
  loading: boolean;
  error: string | null;
  onFilterChange: (field: string, value: string) => void;
  onClassSelect: (classCode: string) => void;
  onBack: () => void;
}

const ClassSelectionView: React.FC<ClassSelectionViewProps> = ({
  classFilters,
  selectedFilters,
  loading,
  error,
  onFilterChange,
  onClassSelect,
  onBack,
}) => {
  const [searchQuery, setSearchQuery] = useState('');

  // 筛选后的班级列表(支持搜索)
  const filteredClasses = useMemo(() => {
    if (!classFilters?.classes_data) return [];
    if (!searchQuery.trim()) return classFilters.classes_data;

    const query = searchQuery.toLowerCase().trim();
    return classFilters.classes_data.filter((classItem) =>
      classItem.class_name.toLowerCase().includes(query)
    );
  }, [classFilters?.classes_data, searchQuery]);

  return (
    <div className="min-h-[500px] flex flex-col">
      {/* 头部 - 减少高度 */}
      <div className="bg-gradient-to-br from-indigo-500 to-purple-600 text-white px-6 py-4">
        <div className="flex items-center justify-between mb-3">
          <button
            onClick={onBack}
            className="text-white/80 hover:text-white transition-colors flex items-center"
          >
            <ChevronRight className="w-5 h-5 rotate-180 mr-1" />
            <span className="text-sm">返回</span>
          </button>
          <div className="flex items-center space-x-2">
            <GraduationCap className="w-6 h-6" />
            <h2 className="text-xl font-bold">选择班级</h2>
          </div>
          <div className="w-12"></div>
        </div>
        <p className="text-indigo-100 text-center text-xs">
          {classFilters ? `共 ${classFilters.total_classes} 个班级` : '加载中...'}
        </p>
      </div>

      {/* 内容区域 */}
      <div className="flex-1 p-4 overflow-y-auto max-h-[450px]">
        {loading && (
          <div className="space-y-4">
            <FilterSkeleton />
            <SearchSkeleton />
            <SkeletonList count={5} />
          </div>
        )}

        {error && (
          <div className="text-center py-8">
            <p className="text-red-500">{error}</p>
          </div>
        )}

        {!loading && !error && classFilters && (
          <div className="space-y-4">
            {/* 筛选条件 - 水平排列 */}
            {classFilters.filters.length > 0 && (
              <div className="pb-4 border-b border-gray-200">
                <div className="flex flex-wrap gap-2">
                  {classFilters.filters.map((filter) => (
                    <FilterButton
                      key={filter.field}
                      filter={filter}
                      value={selectedFilters[filter.field] || ''}
                      onChange={(value) => onFilterChange(filter.field, value)}
                    />
                  ))}
                </div>
              </div>
            )}

            {/* 搜索框 */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="搜索班级名称..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-3 bg-gradient-to-r from-gray-50 to-gray-100 border-2 border-gray-200 rounded-xl focus:border-indigo-400 focus:ring-2 focus:ring-indigo-200 focus:bg-white transition-all duration-200 outline-none text-sm"
              />
            </div>

            {/* 班级列表 - 简化显示 */}
            <div className="space-y-2">
              {filteredClasses.length > 0 ? (
                filteredClasses.map((classItem) => (
                  <button
                    key={classItem.class_code}
                    onClick={() => onClassSelect(classItem.class_code)}
                    className="w-full px-4 py-3 bg-gradient-to-r from-gray-50 to-gray-100 hover:from-indigo-50 hover:to-purple-50 rounded-xl border-2 border-gray-200 hover:border-indigo-400 transition-all duration-200 text-left group"
                  >
                    <div className="flex items-center justify-between">
                      <span className="font-medium text-gray-800 group-hover:text-indigo-600 transition-colors">
                        {classItem.class_name}
                      </span>
                      <ChevronRight className="w-5 h-5 text-gray-400 group-hover:text-indigo-500 transition-colors" />
                    </div>
                  </button>
                ))
              ) : (
                <div className="text-center py-12 text-gray-400">
                  <Search className="w-12 h-12 mx-auto mb-3 opacity-30" />
                  <p>没有找到符合条件的班级</p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

/** 骨架屏组件 - 带渐变色和炫酷呼吸效果 */
const SkeletonList: React.FC<{ count: number }> = ({ count }) => {
  return (
    <div className="space-y-3">
      {Array.from({ length: count }).map((_, index) => (
        <div
          key={index}
          className="relative w-full h-16 rounded-xl overflow-hidden"
          style={{
            animation: 'breathe 2s ease-in-out infinite',
            animationDelay: `${index * 200}ms`,
            background: 'linear-gradient(90deg, #e5e7eb 0%, #f3f4f6 50%, #e5e7eb 100%)',
          }}
        >
          {/* 流光动画层 */}
          <div
            className="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent"
            style={{
              animation: 'shimmer 2.5s infinite',
              animationDelay: `${index * 200}ms`,
              opacity: 0.6,
            }}
          />
          
          {/* 脉冲光晕层 */}
          <div
            className="absolute inset-0"
            style={{
              animation: 'pulse-glow 2s ease-in-out infinite',
              animationDelay: `${index * 200}ms`,
              background: 'radial-gradient(circle at center, rgba(99, 102, 241, 0.15) 0%, transparent 70%)',
            }}
          />
          
          {/* 内容骨架 */}
          <div className="absolute inset-0 p-4 flex items-center justify-between">
            {/* 左侧图标和文字 */}
            <div className="flex items-center space-x-3">
              <div 
                className="w-10 h-10 rounded-lg bg-gray-300/60"
                style={{
                  animation: 'skeleton-pulse 1.5s ease-in-out infinite',
                  animationDelay: `${index * 200}ms`,
                }}
              />
              <div className="space-y-2">
                <div 
                  className="w-32 h-4 rounded bg-gray-300/60"
                  style={{
                    animation: 'skeleton-pulse 1.5s ease-in-out infinite',
                    animationDelay: `${index * 200 + 100}ms`,
                  }}
                />
                <div 
                  className="w-24 h-3 rounded bg-gray-300/40"
                  style={{
                    animation: 'skeleton-pulse 1.5s ease-in-out infinite',
                    animationDelay: `${index * 200 + 200}ms`,
                  }}
                />
              </div>
            </div>
            {/* 右侧箭头 */}
            <div 
              className="w-5 h-5 rounded bg-gray-300/40"
              style={{
                animation: 'skeleton-pulse 1.5s ease-in-out infinite',
                animationDelay: `${index * 200 + 300}ms`,
              }}
            />
          </div>
        </div>
      ))}
      
      {/* 添加自定义动画 */}
      <style jsx>{`
        @keyframes shimmer {
          0% {
            transform: translateX(-100%);
          }
          100% {
            transform: translateX(100%);
          }
        }
        
        @keyframes breathe {
          0%, 100% {
            transform: scale(1);
            opacity: 1;
          }
          50% {
            transform: scale(1.01);
            opacity: 0.95;
          }
        }
        
        @keyframes pulse-glow {
          0%, 100% {
            opacity: 0.3;
            transform: scale(1);
          }
          50% {
            opacity: 0.6;
            transform: scale(1.05);
          }
        }
        
        @keyframes skeleton-pulse {
          0%, 100% {
            opacity: 0.4;
          }
          50% {
            opacity: 0.8;
          }
        }
      `}</style>
    </div>
  );
};

/** 筛选按钮骨架屏 - 炫酷呼吸效果 */
const FilterSkeleton: React.FC = () => {
  return (
    <div className="flex flex-wrap gap-2 pb-4 border-b border-gray-200">
      {Array.from({ length: 3 }).map((_, index) => (
        <div
          key={index}
          className="relative h-10 w-24 rounded-lg overflow-hidden"
          style={{
            animation: 'breathe 2s ease-in-out infinite',
            animationDelay: `${index * 150}ms`,
            background: 'linear-gradient(90deg, #e5e7eb 0%, #f3f4f6 50%, #e5e7eb 100%)',
          }}
        >
          {/* 流光层 */}
          <div
            className="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent"
            style={{
              animation: 'shimmer 2.5s infinite',
              animationDelay: `${index * 150}ms`,
              opacity: 0.6,
            }}
          />
          {/* 脉冲光晕 */}
          <div
            className="absolute inset-0"
            style={{
              animation: 'pulse-glow 2s ease-in-out infinite',
              animationDelay: `${index * 150}ms`,
              background: 'radial-gradient(circle at center, rgba(99, 102, 241, 0.12) 0%, transparent 70%)',
            }}
          />
        </div>
      ))}
    </div>
  );
};

/** 搜索框骨架屏 - 炫酷呼吸效果 */
const SearchSkeleton: React.FC = () => {
  return (
    <div 
      className="relative w-full h-12 rounded-xl overflow-hidden"
      style={{
        animation: 'breathe 2s ease-in-out infinite',
        background: 'linear-gradient(90deg, #e5e7eb 0%, #f3f4f6 50%, #e5e7eb 100%)',
      }}
    >
      {/* 流光层 */}
      <div
        className="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent"
        style={{
          animation: 'shimmer 2.5s infinite',
          opacity: 0.6,
        }}
      />
      {/* 脉冲光晕 */}
      <div
        className="absolute inset-0"
        style={{
          animation: 'pulse-glow 2s ease-in-out infinite',
          background: 'radial-gradient(circle at 15% 50%, rgba(99, 102, 241, 0.15) 0%, transparent 70%)',
        }}
      />
      {/* 内容骨架 */}
      <div className="absolute inset-0 p-3 flex items-center">
        <div 
          className="w-5 h-5 rounded bg-gray-300/60"
          style={{
            animation: 'skeleton-pulse 1.5s ease-in-out infinite',
          }}
        />
        <div 
          className="ml-3 w-32 h-4 rounded bg-gray-300/60"
          style={{
            animation: 'skeleton-pulse 1.5s ease-in-out infinite',
            animationDelay: '100ms',
          }}
        />
      </div>
    </div>
  );
};

/** 学校列表骨架屏 - 炫酷蓝色呼吸效果 */
const SchoolSkeletonList: React.FC<{ count: number }> = ({ count }) => {
  return (
    <div className="space-y-3">
      {Array.from({ length: count }).map((_, index) => (
        <div
          key={index}
          className="relative w-full h-20 rounded-xl overflow-hidden"
          style={{
            animation: 'breathe-school 2s ease-in-out infinite',
            animationDelay: `${index * 200}ms`,
            background: 'linear-gradient(90deg, #dbeafe 0%, #e0e7ff 50%, #dbeafe 100%)',
          }}
        >
          {/* 流光动画层 - 蓝色主题 */}
          <div
            className="absolute inset-0 bg-gradient-to-r from-transparent via-white to-transparent"
            style={{
              animation: 'shimmer-school 2.5s infinite',
              animationDelay: `${index * 200}ms`,
              opacity: 0.7,
            }}
          />
          
          {/* 脉冲光晕层 - 蓝色 */}
          <div
            className="absolute inset-0"
            style={{
              animation: 'pulse-glow-school 2s ease-in-out infinite',
              animationDelay: `${index * 200}ms`,
              background: 'radial-gradient(circle at center, rgba(59, 130, 246, 0.25) 0%, transparent 70%)',
            }}
          />
          
          {/* 内容骨架 */}
          <div className="absolute inset-0 p-4 flex items-center justify-between">
            {/* 左侧图标和文字 */}
            <div className="flex items-center space-x-3">
              <div 
                className="w-12 h-12 rounded-lg bg-blue-300/70"
                style={{
                  animation: 'skeleton-pulse-school 1.5s ease-in-out infinite',
                  animationDelay: `${index * 200}ms`,
                }}
              />
              <div className="space-y-2">
                <div 
                  className="w-40 h-5 rounded bg-blue-300/70"
                  style={{
                    animation: 'skeleton-pulse-school 1.5s ease-in-out infinite',
                    animationDelay: `${index * 200 + 100}ms`,
                  }}
                />
                <div 
                  className="w-28 h-3 rounded bg-blue-300/50"
                  style={{
                    animation: 'skeleton-pulse-school 1.5s ease-in-out infinite',
                    animationDelay: `${index * 200 + 200}ms`,
                  }}
                />
              </div>
            </div>
            {/* 右侧箭头 */}
            <div 
              className="w-6 h-6 rounded bg-blue-300/50"
              style={{
                animation: 'skeleton-pulse-school 1.5s ease-in-out infinite',
                animationDelay: `${index * 200 + 300}ms`,
              }}
            />
          </div>
        </div>
      ))}
      
      {/* 添加学校选择专用动画 */}
      <style jsx>{`
        @keyframes shimmer-school {
          0% {
            transform: translateX(-100%);
          }
          100% {
            transform: translateX(100%);
          }
        }
        
        @keyframes breathe-school {
          0%, 100% {
            transform: scale(1);
            opacity: 1;
          }
          50% {
            transform: scale(1.01);
            opacity: 0.95;
          }
        }
        
        @keyframes pulse-glow-school {
          0%, 100% {
            opacity: 0.3;
            transform: scale(1);
          }
          50% {
            opacity: 0.7;
            transform: scale(1.05);
          }
        }
        
        @keyframes skeleton-pulse-school {
          0%, 100% {
            opacity: 0.5;
          }
          50% {
            opacity: 0.9;
          }
        }
      `}</style>
    </div>
  );
};
